package com.yituo.mjworld.mvc.action.admin;

import com.yituo.mjworld.core.annotation.Check;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.entity.other.RecordAgentRequest;
import com.yituo.mjworld.mvc.entity.rule.ProAgent;
import com.yituo.mjworld.mvc.entity.web.WebUser;
import com.yituo.mjworld.mvc.service.impl.AdminServiceImpl;
import com.yituo.mjworld.mvc.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * 管理员模块
 */
@Component
public class AdminAction {
  @Autowired
  AdminServiceImpl adminService;

  @Autowired
  UserServiceImpl userService;

  /**
   * 创建用户接口!
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Check(form = ProAgent.class)
  public void createUser(MyHttpRequest req, MyHttpResponse res) throws IOException {
    WebUser currentUser = req.getCurrentUser();
    // 超级管理员录入省级代理
    ProAgent agent = (ProAgent) req.getForm();
    WebUser newUser = new WebUser();
    try {
      BeanUtils.populate(newUser, agent.getParam());
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    newUser.setReferrer(currentUser.getId());
    newUser.setRegisterDate(new Date());
    res.setResult(adminService.createUser(currentUser, newUser));
  }


  /**
   * 申请成为代理
   *
   * @param req
   * @param res
   * @throws IOException
   */
  public void requestAgent(MyHttpRequest req, MyHttpResponse res) throws IOException {
    // 检查用户是否拥有二维码

    WebUser parentUser = userService.getReferrer(req.getCurrentUser().getId());
    if (parentUser == null) {
      // 自由人
      // TODO:生成二维码
      return;
    }
    res.setResult(adminService.requestAgent(req.getCurrentUser(), parentUser));
  }

  /**
   * 处理代理申请
   */
  public void processAgentRequest(MyHttpRequest req, MyHttpResponse res) throws IOException {
    WebUser user = null;
    int id = -1;
    int processStatus = 0;
    String processMsg = null;
    try {
      user = req.getCurrentUser();
      id = Integer.parseInt(req.getParameter("id"));
      processStatus = Integer.parseInt(req.getParameter("processStatus"));
      processMsg = req.getParameter("processMsg");
      if (id <= 0 || processStatus < RecordAgentRequest.STATUS_WAIT || processStatus > RecordAgentRequest.STATUS_PASS) {
        res.failedFor302("参数不符合规范!");
        return;
      } else {
        res.setResult(adminService.processRueqest(id, processStatus, processMsg, user.getId()));
      }
    } catch (Exception e) {
      e.printStackTrace();
      res.failedFor302("前端参数转换异常!");
    }
  }
}
